﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PSI.Models;
using System.IO;
using PSI.Services;

namespace PSI.Controllers
{
    public class KnowledgeController : Controller
    {
        //
        // GET: /Knowledge/
        public class trchile:KnowledgeTheme {
            public string text { get; set; }

            public bool expanded { get; set; }

            public bool leaf { get; set; }

            public string servicepath { get; set; }

        }

        public ActionResult Index()
        {
            if (Request["id"] != null)
            {
                ViewBag.id = Request["id"].ToString();
            }
            ViewBag.UserName = Services.UserService.GetLoginUser().Name;
            return View();

        }

        public ActionResult IndexBacks()
        {
            ViewBag.UserName = Services.UserService.GetLoginUser().Name;
            return View();
        
        }

        [HttpPost]
        public ActionResult AddEssay(KnowledgeType model)
        {
            var result = new Services.KnowledgeService().AddOREditEssayType(model);

            if (result > 0)
            {
                return Json(new { success  = true,msg="" });
            }
            else
            {
                return Json(new { success = false, msg = "" });
            }
             
        }

        [HttpPost]
        public ActionResult GetKtypeItems()
        { 
           var items=new Services.KnowledgeService().AllKtypeitems();
           var json = new { Data = items };
           return Json(json);
        }

        [HttpPost]
        public ActionResult DeleteKtype(string id)
        {
            var item = new Services.KnowledgeService().AllKtypeitems().Where(a=>a.id==Guid.Parse(id)).Single();

            if (item.KthemeItem.Count() != 0)
            {
                return Json(new { success = false, msg = "该类别下有文章，无法删除！" });
            }

            var result = new Services.KnowledgeService().DelEssaySing(id);

            if (result > 0)
            {
                return Json(new {success=true,msg=""});
            }
            else
            {
                return Json(new { success = false, msg = "数据库或网络问题，操作失败！" });
            }
        }

        [HttpPost]
        public ActionResult UploadFile()
        {
            try
            {
                var formname = this.Request.Form["filename"];
                var formtype = this.Request.Form["filetype"];

                var ty = formtype == "1" ? "file1" : "file2";
                
                var files = this.Request.Files[ty];

                var path = this.Server.MapPath("~");
                path += @"\uploads";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                var fileName = path + @"\" + formname;

                 files.SaveAs(fileName);

                 return Content("{success: true}");
            }
            catch (Exception ex)
            {
                return Content("{success: false, msg: '" + ex.Message + "'}");
            }
        
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ReleaseEassy()
        {
            var result = new Services.KnowledgeService().ReleaseEassy(this.Request.Form);
            if (result > 0)
            {
                return Content("{success:true}");
            }
            else
            {
                return Content("{success:false}");
            }
        }

        [HttpPost]
        public ActionResult GetEassyAcrItems(string pareid)
        {
            var result = new Services.KnowledgeService().GetAllAcr(pareid);

            return Json(new {Data=result });
        }

        [HttpPost]
        public ActionResult DelAcr(string id)
        {
            var result = new Services.KnowledgeService().DeleteAcrSing(id);
            if (result > 0)
            {
                return Json(new { success = true });
            }
            else
            {
                return Json(new { success = false });
            }
        }

        [HttpPost]
        public ActionResult GetTress()
        {
            var Ktype = new Services.KnowledgeService().AllKtypeitems();
            var result = new List<object>();
            for (int i = 0; i < Ktype.Count; i++)
            {
                var trssroot = new object();
                if (Ktype[i].KthemeItem.Count > 0)
                {
                  
                    List<trchile> chile = (from item in Ktype[i].KthemeItem select new trchile { text = item.title, Contents = item.Contents, FileOne = item.FileOne, FileTwo = item.FileTwo, leaf = true, id = item.id }).ToList();
                    trssroot = new { text = Ktype[i].name, id = Ktype[i].id, expanded = true, children = chile, expandable =true };
                }
                else
                {
                    trssroot = new { text = Ktype[i].name, id = Ktype[i].id, expandable = false };
                }
                result.Add(trssroot);
            }
            return Json(result);
        }


        public ActionResult DownLoad(string id,int num)
        {
            var path = this.Server.MapPath("~");
            path += @"uploads";
            var filename = "";
            var items = new Services.KnowledgeService().GetSingAcr(id);
            if (num == 1)
            {
                path += @"\" + items.FileOne;
                var cc = (items.FileOne).Split('_');
                filename = cc[1];
            }
            else
            {
                path += @"\" + items.FileTwo;
                var cc = (items.FileTwo).Split('_');
                filename = cc[1];
            }

            return File(path, "application/vnd.ms-excel", filename);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddKreply()
        {
            var result = new Services.KnowledgeService().AddReply(this.Request.Form);
            if (result > 0)
            {
                return Json(new { success = true });
            }
            else
            {
                return Json(new { success = false });
            }
        
        }

        [HttpPost]
        public ActionResult GetKreplyItem(string  id)
        {
            var list = new Services.KnowledgeService().GetAllReply(id);

            return Json(new { Data = list });
        
        }


        public ActionResult MainPage()
        { 
          
           var data=new Services.KnowledgeService().MainPageInfo();
           
           var cc=new {Data=data};

           return Json(cc,JsonRequestBehavior.AllowGet);
        }


    }
}
